<template>
  <client-only>
    <el-dialog :model-value="visible" :destroy-on-close="true" :append-to-body="true" title="收银台" width="500px" align-center @close="onClose">
      <el-form v-if="orderInfo.orderStatus === 0" ref="formRef" :model="orderModel">
        <div class="course-info">
          <img :src="courseInfo.courseLogo" class="course-info-img" />
          <div class="course-info-title">
            {{ courseInfo.courseName }}
          </div>
          <div class="course-info-price">￥{{ courseInfo.coursePrice }}</div>
        </div>
        <el-form-item label="支付方式：" prop="payType">
          <el-radio-group v-model="orderModel.payType" @change="handleChange">
            <el-radio v-for="(item, index) in payTypes" :key="index" :label="item.code">
              {{ item.desc }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="orderModel.payType === 100" label="可用金额：" prop="remark"> ￥{{ availableAmount }}元 </el-form-item>
        <el-form-item label="订单备注：" prop="remark">
          <el-input v-model="orderModel.remark" maxlength="25" placeholder="若需备注，请在这里输入" show-word-limit />
        </el-form-item>
      </el-form>

      <div v-if="orderInfo.orderStatus > 0" class="course-qrcode">
        <div class="course-qrcode-title">
          正在使用
          <span v-for="(item, index) in payTypes" :key="index">
            <span v-if="orderInfo.payType === item.code"> {{ item.desc }}</span>
          </span>
          支付：￥{{ orderInfo.coursePrice.toFixed(2) }}
        </div>

        <canvas v-if="orderInfo.orderStatus === 1" id="canvas" />
        <div v-if="orderInfo.orderStatus === 2" class="order-info-title">
          <img src="~/assets/svg/success.svg" class="order-info-img" />
          <div>支付成功</div>
        </div>
        <div v-if="orderInfo.orderStatus === 3" class="order-info-title">
          <img src="~/assets/svg/error.svg" class="order-info-img" />
          <div>支付失败</div>
        </div>

        <div v-if="orderModel.payType !== 100" class="course-qrcode-desc">请扫描二维码完成订单</div>
        <div v-if="orderModel.payType !== 100" class="course-qrcode-tips">
          提示: <br />
          支付成功前请勿手动关闭页面 <br />
          二维码两小时内有效，请及时扫码支付
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="danger" @click="onClose">关闭</el-button>
          <el-button v-if="orderInfo.orderStatus === 0" v-loading="loading" type="primary" @click="onSubmit">确认购买</el-button>
        </span>
      </template>
    </el-dialog>
  </client-only>
</template>
<script setup>
  // 表单
  import { courseApi } from '~/api/course.js'
  import QRCode from 'qrcode'
  import { userApi } from '~/api/user'

  const courseInfo = ref({})
  // 订单
  const orderModel = ref({
    payType: 2,
    remark: ''
  })
  const orderInfo = ref({
    // 0订单没生成，1待支付，2成功支付，3支付失败，4关闭支付
    orderStatus: 0
  })
  const payTypes = ref([
    { code: 11, desc: '微信' },
    { code: 21, desc: '支付宝' },
    { code: 100, desc: '余额' }
  ])
  let orderQueryInterval = null

  const availableAmount = ref(0)
  const handleChange = (item) => {
    if (item === 100) {
      userApi.getUserInfo().then((res) => {
        availableAmount.value = res.availableAmount
      })
    }
  }

  // 下单
  const onSubmit = async () => {
    if (loading.value === true) {
      ElMessage.warning('正在处理...')
      return
    }
    loading.value = true
    try {
      let res
      if (courseInfo.value.orderNo) {
        // 继续支付
        res = await userApi.continuePay({ orderNo: courseInfo.value.orderNo, payType: orderModel.value.payType })
      } else {
        // 下单
        orderModel.value.courseId = courseInfo.value.id
        res = await courseApi.createOrder(orderModel.value)
      }
      orderInfo.value = res

      if (orderInfo.value.orderStatus === 2) {
        ElMessage.success('支付成功')
      } else {
        await nextTick(() => {
          QRCode.toCanvas(document.getElementById('canvas'), res.payMessage, { width: 250, height: 250 })
        })

        orderQueryInterval = setInterval(() => {
          if (orderInfo.value.orderStatus === 1) {
            orderQuery(orderInfo.value.orderNo)
          }
        }, 2000)
      }
    } finally {
      loading.value = false
    }
  }

  // 订单查询
  async function orderQuery(orderNo) {
    const res = await courseApi.orderInfoView(orderNo)
    orderInfo.value = res
    if (res.orderStatus === 2) {
      ElMessage.success('支付成功')
    } else if (res.orderStatus === 3) {
      ElMessage.error('支付失败')
    }
  }

  // 打开和关闭
  const onOpen = (item) => {
    if (item) {
      Object.assign(courseInfo.value, item)
    }
    visible.value = true
  }
  defineExpose({ onOpen })

  const onClose = () => {
    visible.value = false
    courseInfo.value = {}
    if (orderInfo.value.orderStatus === 2) {
      emit('refresh')
    }
    orderInfo.value.orderStatus = 0
    clearInterval(orderQueryInterval)
  }
  const emit = defineEmits(['refresh'])
  const visible = ref(false)
  const loading = ref(false)
</script>
<style lang="scss" scoped>
  .el-form {
    padding: 10px 20px;
  }
  .course-info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 0 30px;
    div {
      padding: 0 10px;
    }
    .course-info-img {
      width: 120px;
      height: auto;
    }
    .course-info-title {
      width: 200px;
    }
  }

  .course-qrcode {
    padding: 0 20px;
    text-align: center;
    .course-qrcode-desc {
      margin: 0 auto;
      width: 160px;
      padding: 13px 0 13px 70px;
      height: 50px;
      line-height: 50px;
      font-size: 14px;
      color: #fff;
      background: url()
        no-repeat 20px center #445f85;
    }

    .order-info-img {
      height: 100px;
      width: auto;
    }
    .course-qrcode-tips {
      margin-top: 30px;
      text-align: left;
    }

    .order-info-title {
      margin: 60px 0;
    }
  }
</style>
